package com.alipay.rebate.shop.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.*;
import java.util.zip.GZIPOutputStream;

public class Test {

    final static Base64.Encoder encoder = Base64.getEncoder();
    /**
     * 给字符串加密
     * @param text
     * @return
     */
    public static String base64Encode(String text) {
        byte[] textByte = new byte[0];
        try {
            textByte = text.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String encodedText = encoder.encodeToString(textByte);
        return encodedText;
    }

    /**
     * 使用gzip进行压缩
     */
    public static String compress(String primStr) {
        if (primStr == null || primStr.length() == 0) {
            return primStr;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = null;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(primStr.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (gzip != null) {
                try {
                    gzip.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new sun.misc.BASE64Encoder().encode(out.toByteArray());
    }

    public static String sendPost(String postUrl, Map<String, String> paraMap){
        if(paraMap == null){
            paraMap = new HashMap<>();
        }
        paraMap= new TreeMap<>(paraMap);
        StringBuilder sb = new StringBuilder();
        List<NameValuePair> params = new ArrayList<>();
        for(Map.Entry<String,String> entry : paraMap.entrySet()){
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return doPost(postUrl,params);
    }

    public static String doPost(String url, List<NameValuePair> params) {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        try {
            post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse response = client.execute(post);
            String res = EntityUtils.toString(response.getEntity());
            System.out.println(res);
            return res;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String userInfo(){
        TreeMap<String,String> paraMap = new TreeMap<>();
        paraMap.put("uphone","18333051754");
        paraMap.put("user_name","test");
        paraMap.put("avatar",null);
        paraMap.put("money","5.70");
        paraMap.put("jifen","100");
        paraMap.put("agent_create_time",null);
        paraMap.put("alipay","18333051754");
        paraMap.put("alipay_name","test");
        paraMap.put("login_time","2019-09-16 18:30:49");
        paraMap.put("create_time","2019-09-16 18:30:49");
        paraMap.put("wx_unionid","ADDFVDDFDdf");
        paraMap.put("user_level","1");
        paraMap.put("agent_level","普通会员");
        String jsonString = JSON.toJSONString(paraMap);
        String compress = compress(jsonString);
        String base64Encode = base64Encode(compress);
        return base64Encode;
    }

    public static String sign(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(s.getBytes("utf-8"));
            return toHex(bytes);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String toHex(byte[] bytes) {
        final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i=0; i<bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }

    public static Object  test() throws Exception {
        String url = "http://test.ujuec.com/gw";
        TreeMap<String,String> paraMap = new TreeMap<>();
        paraMap.put("service","ujuec_user_import");
        paraMap.put("appKey","E14V0pwyTZrJZAB9");
        paraMap.put("data",userInfo());
        paraMap.put("timestamp",String.valueOf(System.currentTimeMillis()));
        String silink = "";
        for (Map.Entry<String, String> entry : paraMap.entrySet())
        {
            try{
                silink += (silink==""?"":"&")+entry.getKey()+"="+entry.getValue();
            }catch(Exception e){}

        }
        String sign = sign(silink + "c07627d655f824fee49b0252d3b89595");
        paraMap.put("sign",sign);
        Object getObj = sendPost(url,paraMap);
        return getObj;
    }
}
